package myJs.admin.sampleManage

import myJs.Implicits._
import myJs.admin.editSample.EditSample
import myJs.admin.viewSample.ViewSample
import myJs.cps.BootstrapTableCp.Column
import myJs.cps.{BootstrapTableCp, Style}
import myJs.myPkg.{MyFetch, SwalOptions, swal}
import myJs.tool.Pojo._
import myJs.tool.Tool
import myJs.CpLayer
import myJs.api.Api
import myJs.common.LabModalCp
import myJs.cps.project._
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.Sample.{FreezerInfo, TestData}
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.Fragment
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.web.html._
import typings.csstype.csstypeStrings
import upickle.default._

import scala.collection.immutable.SeqMap

/**
 * Created by yz on 21/1/2022
 */
@react object Cp {

  val curPage = SampleManage
  type Props = Unit

  val component = FunctionalComponent[Props] { props =>

    val (datas, setDatas) = useState(List.empty[ujson.Obj])
    val (basicInfoShow, setBasicInfoShow) = useState(false)
    val (freezerInfoShow, setFreezerInfoShow) = useState(false)
    val (labShow, setLabShow) = useState(false)
    val (testInfoShow, setTestInfoShow) = useState(false)
    val (sampleId, setSampleId) = useState("")
    val (qrcodeId, setQrcodeId) = useState("")
    val (qrcodeShow, setQrcodeShow) = useState(false)

    useEffect(() => {
      FTool.refreshTableB()
    }, List()
    )

    object FTool {

      def delete(id: String) = () => {
        val options = SwalOptions(title = "", text = "确定要删除此数据吗？", `type` = "warning", showCancelButton = true,
          showConfirmButton = true, confirmButtonClass = Tool.confirmButtonClass, confirmButtonText = "确定",
          closeOnConfirm = false, cancelButtonText = "取消", showLoaderOnConfirm = true,
          cancelButtonClass = Tool.cancelButtonClass)
        swal(options, () => {
          Api.sample.delete(id).map { str =>
            refreshTableB().map { x =>
              swal(SwalOptions(title = "成功", text = "删除成功", `type` = "success"))
            }
          }
        })
      }

      def refreshTableB = () => {
        Api.sample.all.map { response =>
          setDatas(response)
        }
      }

      def qrcodeShowChange = (v: Boolean) => {
        setQrcodeShow(v)
      }

      def showQrcode(idStr: String) = () => {
        setQrcodeId(idStr)
        setQrcodeShow(true)
      }

      def basicInfoShow(curSampleId: String) = () => {
        setSampleId(curSampleId)
        setBasicInfoShow(true)
      }

      def freezerInfoShow(curSampleId: String) = () => {
        setSampleId(curSampleId)
        setFreezerInfoShow(true)
      }

      def labShow(curSampleId: String) = () => {
        setSampleId(curSampleId)
        setLabShow(true)
      }

      def freezerInfoShowChange = (v: Boolean) => {
        setFreezerInfoShow(v)
      }

      def labShowChange = (v: Boolean) => {
        setLabShow(v)
      }

      def testInfoShow(curSampleId: String) = () => {
        setSampleId(curSampleId)
        setTestInfoShow(true)
      }

      def lock(curSampleId: String) = () => {
        Api.sample.lock(curSampleId).flatMap { x =>
          FTool.refreshTableB()
        }
        ()
      }

      def unlock(curSampleId: String) = () => {
        Api.sample.unlock(curSampleId).flatMap { x =>
          FTool.refreshTableB()
        }
        ()
      }

      def operateFmt = (v: ujson.Value, row: ujson.Obj) => {
        span(
          if (row.obj.isDefinedAt("locked") && row("locked").bool) {
            button(style := Style(cursor = csstypeStrings.pointer), className := "btn btn-warning btn-xs myUpdateShow",
              title := "解锁", data - "value" := s"${row("id").str}",onClick:=FTool.unlock(row("id").str),
              span(
                em(className := "fa fa-unlock", "解锁")
              )
            )
          } else {
            Fragment(
              a(style := Style(cursor = csstypeStrings.pointer), className := "btn btn-success btn-xs myUpdateShow",
                title := "修改", data - "value" := s"${row("id").str}", href := s"#${EditSample.absolutePath}?id=${row("id").str}",
                span(
                  em(className := "fa fa-edit", "修改")
                )
              ),
              " ",
              button(style := Style(cursor = csstypeStrings.pointer), className := "btn btn-warning btn-xs myUpdateShow",
                title := "锁定", data - "value" := s"${row("id").str}", onClick := FTool.lock(row("id").str),
                span(
                  em(className := "fa fa-lock", "锁定")
                )
              )
            )
          },
          " ",
          a(style := Style(cursor = csstypeStrings.pointer), className := "btn btn-danger btn-xs",
            title := "删除", onClick := FTool.delete(s"${row("id").str}"),
            target := "_blank",
            span(
              em(className := "fa fa-remove", "删除")
            )
          )
        )()
      }

      def tbFmt(field: String) = (v: ujson.Value, row: ujson.Obj) => {
        field match {
          case "id" =>
            span(
              a(href := s"${ViewSample.absolutePath}?id=${row("id").str}", s"${v.str}"),
              " ",
              i(className := "fa fa-qrcode", style := Style(cursor = csstypeStrings.pointer),
                onClick := FTool.showQrcode(v.str))
            )()
          case "basicInfo" =>
            button(className := "btn-link get_group_info", title := "查看",
              onClick := FTool.basicInfoShow(row("id").str),
              i(className := "fa fa-search-plus"))()
          case "freezerInfo" =>
            Tool.freezerInfoFmt(v = v, row = row, freezerInfoShow = FTool.freezerInfoShow)
          case "lab" =>
            Tool.labFmt(v = v, row = row, labShow = FTool.labShow)
          case "tests" =>
            val testInfos = v.transform(reader[List[TestData]])
            if (testInfos.nonEmpty) {
              button(className := "btn-link get_group_info", title := "查看",
                onClick := FTool.testInfoShow(row("id").str),
                i(className := "fa fa-search-plus"))()
            } else {
              span("无")()
            }
          case _ => span(v.myStr)()
        }
      }

      def comVFmt(fileTitle: String) = (v: ujson.Value, row: ujson.Obj) => {
        fileTitle match {
          case _ => v.toString
        }
      }

      def basicInfoShowChange = (v: Boolean) => {
        setBasicInfoShow(v)
      }

      def testInfoShowChange = (v: Boolean) => {
        setTestInfoShow(v)
      }

    }

    val map = SeqMap("id" -> "样本编号", "basicInfo" -> "基本信息", "freezerInfo" -> "冰箱信息", "lab" -> "实验信息",
      "tests" -> "测试信息",
      "updateTime" -> "更新时间")

    val basicColumns = map.map { case (k, v) =>
      val searchKind = k match {
        case "updateTime" => DateSearch
        case _ => TextSearch
      }
      val fmt = FTool.tbFmt(k)
      val comVF = FTool.comVFmt(v)
      Column(field = k, title = v, operable = true, searchKind = searchKind, formatter = fmt, comVF = comVF)
    }.toList
    val operateColumn = Column(field = "operate", title = "操作", formatter = FTool.operateFmt, comVF = FTool.comVFmt(""))
    val columns = basicColumns :+ operateColumn

    CpLayer(title = curPage.titleStr)(
      div(className := "page-content",
        div(className := "row-fluid",
          div(className := "row",
            div(className := "col-md-12 col-sm-12",
              div(className := "portlet light",
                div(className := "portlet-title",
                  div(className := "caption", s"${curPage.titleStr}")
                ),
                div(className := "portlet-body",
                  BootstrapTableCp(columns = columns, datas = datas,
                    pageList = List(10, 25), pageSize = 10),

                  BasicInfoModalCp(show = basicInfoShow, showChange = FTool.basicInfoShowChange, sampleId = sampleId),
                  FreezerInfoModalCp(show = freezerInfoShow, showChange = FTool.freezerInfoShowChange,
                    sampleId = sampleId),
                  LabModalCp(show = labShow, showChange = FTool.labShowChange,
                    sampleId = sampleId),
                  TestInfoWithDetailModalCp(show = testInfoShow, showChange = FTool.testInfoShowChange,
                    sampleId = sampleId),
                  QrcodeModalCp(show = qrcodeShow, showChange = FTool.qrcodeShowChange,
                    sampleId = qrcodeId)

                ),
              )
            )
          )
        )
      )
    )

  }


}
